//
//  MYY_registerView.m
//  meiyinxiang
//
//  Created by 陈李飞 on 2017/11/9.
//  Copyright © 2017年 hbjApple. All rights reserved.
//

#import "MYY_registerView.h"
#import "M80AttributedLabel.h"
#import "MYY_LoginTextField.h"
#import "Stalker.h"
#import "MYY_User.h"
#import "NJXTLoginHelper.h"
#import "MYYLoginCell.h"
#import "JXTColorHelper.h"
#import "XPauthorizationView.h"
#import "MYY_Me_Macro.h"
#import "MYY_LoginMarco.h"
#import "MYY_registerViewController.h"
#import "MYXForgotPasswordViewController.h"
#import "UIView+Additions.h"
#import "CodeButton.h"
#import "MYY_MessageViewModel.h"
#define kregisterVIdentifier @"registerVCellIdentifier"




typedef void(^registerBlock)(NSString *InvitationCode, NSString *account,NSString *code, NSString *password);



@interface MYY_registerView()< UIAlertViewDelegate>
@property(nonatomic, strong) UIView *BGiconView;
@property(nonatomic, strong) UIImageView *iconImageView;
@property(nonatomic, strong) MYY_LoginTextField *InvitationTextField;
@property(nonatomic, strong) MYY_LoginTextField *userTextField;
@property(nonatomic, strong) MYY_LoginTextField *passwordTextField;
@property(nonatomic, strong) MYY_LoginTextField *codeTextField;
@property(nonatomic, strong) UIButton *registerButton;
@property(nonatomic, strong) UIButton *canSeePasswordButton;
@property(nonatomic, strong) UIView *LineView;
@property(nonatomic, strong) CodeButton *XVerificationButton;

@property(nonatomic, strong) MYXHttpManager *MYXHttpManag;


@property(nonatomic, strong) STStalker *stalker;
@property(nonatomic, assign) BOOL needAnimateAfterKeybordHide;

@property(nonatomic, copy) registerBlock registerBlock;
@property(nonatomic, strong) NSMutableArray *users;

@property(nonatomic, strong) MYY_User *willDeleteUser;

@end


@implementation MYY_registerView
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        UIImageView *view = [[UIImageView alloc] init];
        view.userInteractionEnabled = YES;
        view.frame = self.bounds;
        if ( iphone6P) {
            view.image= [UIImage imageNamed:@"6P"];
        }else if (iphone6){
            view.image= [UIImage imageNamed:@"beijing"];
        }
        else{
            view.image= [UIImage imageNamed:@"55s5c"];
        }
        
        view.userInteractionEnabled = YES;
        [self addSubview:view];
        [self addSubview:self.BGiconView];
        [self.BGiconView addSubview:self.iconImageView];
      //  [self addSubview:self.InvitationTextField];
        [self addSubview:self.userTextField];
        [self addSubview:self.passwordTextField];
        [self addSubview:self.codeTextField];
        [self addSubview:self.registerButton];
        [self addSubview:self.LineView];
        [self addSubview:self.XVerificationButton];
        [self addSubview:self.canSeePasswordButton];
        self.needAnimateAfterKeybordHide = YES;
        [self setupUI];
    }
    return self;
}

- (void)setupUI
{
    WS(weakSelf)
    
    [self.InvitationTextField setNormalIcon:@"haoma" highlightIcon:@"haoma" placeholder:@"请输入邀请手机号(选填)" password:NO returnKeyType:UIReturnKeyNext dropDown:YES seperator:YES userSelectBlock:^{
        weakSelf.needAnimateAfterKeybordHide = NO;
        [weakSelf.InvitationTextField setNeedsLayout];
        [weakSelf setNeedsLayout];
    } clearBlock:^{
        weakSelf.InvitationTextField.textField.text = @"";
        weakSelf.passwordTextField.textField.text = @"";
        weakSelf.codeTextField.textField.text = @"";
        weakSelf.userTextField.textField.text = @"";
        [[NSNotificationCenter defaultCenter] postNotificationName:UITextFieldTextDidChangeNotification object:nil];
    }nextBlock:^{
      //  [weakSelf.InvitationTextField.textField becomeFirstResponder];
    } doneBlock:nil];
    
    
    [self.userTextField setNormalIcon:@"shouji" highlightIcon:@"shouji" placeholder:@"请输入手机号码" password:NO returnKeyType:UIReturnKeyNext dropDown:YES seperator:YES userSelectBlock:^{
        weakSelf.needAnimateAfterKeybordHide = NO;
        [weakSelf.userTextField setNeedsLayout];
        [weakSelf setNeedsLayout];
    } clearBlock:^{
        weakSelf.InvitationTextField.textField.text = @"";
        weakSelf.passwordTextField.textField.text = @"";
        weakSelf.codeTextField.textField.text = @"";
        weakSelf.userTextField.textField.text = @"";
        [[NSNotificationCenter defaultCenter] postNotificationName:UITextFieldTextDidChangeNotification object:nil];
    }nextBlock:^{
        [weakSelf.passwordTextField.textField becomeFirstResponder];
    } doneBlock:nil];
    
    [self.codeTextField setNormalIcon:@"yanzhengma" highlightIcon:@"yanzhengma" placeholder:@"请输入验证码" password:NO returnKeyType:UIReturnKeyNext dropDown:NO seperator:NO userSelectBlock:^{
        weakSelf.needAnimateAfterKeybordHide = NO;
        [weakSelf.codeTextField setNeedsLayout];
        [weakSelf setNeedsLayout];
    } clearBlock:^{
        weakSelf.InvitationTextField.textField.text = @"";
        weakSelf.passwordTextField.textField.text = @"";
        weakSelf.codeTextField.textField.text = @"";
        weakSelf.userTextField.textField.text = @"";
        [[NSNotificationCenter defaultCenter] postNotificationName:UITextFieldTextDidChangeNotification object:nil];
    }nextBlock:^{
        //  [weakSelf.InvitationTextField.textField becomeFirstResponder];
    } doneBlock:nil];
    
    
  
    [self.passwordTextField setNormalIcon:@"mima-" highlightIcon:@"mima-" placeholder:@"请输入密码" password:YES returnKeyType:UIReturnKeyJoin dropDown:NO seperator:NO userSelectBlock:nil clearBlock:^{
        weakSelf.InvitationTextField.textField.text = @"";
        weakSelf.passwordTextField.textField.text = @"";
        weakSelf.codeTextField.textField.text = @"";
        weakSelf.userTextField.textField.text = @"";
        [[NSNotificationCenter defaultCenter] postNotificationName:UITextFieldTextDidChangeNotification object:nil];
        
    }nextBlock:nil doneBlock:^{
        [weakSelf login];
    }];
    
    // 开始时的状态
    [self beforeAnimations];
    
    [self.stalker when:UIKeyboardWillShowNotification then:^(NSNotification *notification) {
        NSDictionary *userInfo = notification.userInfo;
        CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
        NSInteger curveOption = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
        if (duration > 0) {
            UIViewAnimationOptions option = (uint)(curveOption << 16);
            [UIView animateWithDuration:duration delay:0 options:option animations:^{
                [weakSelf afterAnimations];
            } completion:nil];
        }
        else {
            [weakSelf afterAnimations];
        }
    }];
    
    [self.stalker when:UIKeyboardWillHideNotification then:^(NSNotification *notification) {
        if (!weakSelf.needAnimateAfterKeybordHide) {
            weakSelf.needAnimateAfterKeybordHide = YES;
            return;
        }
        NSDictionary *userInfo = notification.userInfo;
        CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
        NSInteger curveOption = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
        if (duration > 0) {
            UIViewAnimationOptions option = (uint)(curveOption << 16);
            [UIView animateWithDuration:duration delay:0 options:option animations:^{
                [weakSelf beforeAnimations];
            } completion:nil];
        }
        else {
            [weakSelf beforeAnimations];
        }
    }];
    
    [self.stalker when:UITextFieldTextDidChangeNotification then:^(NSNotification *notification) {
        if (notification.object && ((UIView *)(notification.object)).tag == 10001) {
            // 自动填充
            NSArray *allUsers = [[NJXTLoginHelper helper] listAllUsers];
            __block NSString *willFilledPassword = @"";
            [allUsers enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                MYY_User *cUser = (MYY_User *)obj;
                if ([cUser.account isEqualToString:weakSelf.userTextField.textField.text]) {
                    willFilledPassword = cUser.password;
                    *stop = YES;
                }
            }];
            weakSelf.passwordTextField.textField.text = willFilledPassword;
        }
        
        
        if (![weakSelf.userTextField.textField.text isEqualToString:@""] && ![weakSelf.passwordTextField.textField.text isEqualToString:@""]) {
            [weakSelf updateEnableState:YES hasLogin:NO];
        }
        else {
            [weakSelf updateEnableState:NO hasLogin:NO];
        }
    }];
    [self.userTextField.textField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    [self.passwordTextField.textField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    [self.InvitationTextField.textField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    [self.codeTextField.textField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
}


- (void)setUserList:(NSArray *)userList loginBlock:(void(^)(NSString *InvitationCode, NSString *account,NSString *code, NSString *password))registerBlock
{
    self.users = [NSMutableArray arrayWithArray:userList];
    if (userList.count > 0) {
        MYY_User *defaultUser = [userList firstObject];
        self.userTextField.textField.text = defaultUser.account;
        self.passwordTextField.textField.text = defaultUser.password;
        self.registerButton.enabled = YES;
    }
    self.registerBlock = registerBlock;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
}

// 键盘弹出前的布局
- (void)beforeAnimations
{
    if (iphone5S || iphone4S) {
        self.BGiconView.frame = CGRectMake((WIDTH-105)/2.0, 65, 105, 105);
        self.userTextField.frame = CGRectMake(0, CGRectGetMaxY(self.BGiconView.frame)+39, WIDTH, 50);
        self.BGiconView.layer.cornerRadius =105/2;
    }
    else{
        self.BGiconView.frame = CGRectMake((WIDTH-129)/2.0, 89, 129, 129);
        self.userTextField.frame = CGRectMake(0, CGRectGetMaxY(self.BGiconView.frame)+57, WIDTH, 50);
        self.BGiconView.layer.cornerRadius =129/2;
        
    }
     self.iconImageView.frame = CGRectMake(10, 10, self.BGiconView.frame.size.width-20, self.BGiconView.frame.size.height-20);
    self.iconImageView.layer.cornerRadius = (self.BGiconView.frame.size.width-20)/2;
   // self.userTextField.frame = CGRectMake(0, CGRectGetMaxY(self.InvitationTextField.frame), WIDTH, 50);
    self.codeTextField.frame = CGRectMake(0, CGRectGetMaxY(self.userTextField.frame), WIDTH-120, 50);
    self.passwordTextField.frame = CGRectMake(0, CGRectGetMaxY(self.codeTextField.frame), WIDTH-120, 50);
    self.registerButton.frame = CGRectMake(25, CGRectGetMaxY(self.passwordTextField.frame)+30, WIDTH-50, 40);
    self.XVerificationButton.frame = CGRectMake(WIDTH-80-25, CGRectGetMaxY(self.userTextField.frame), 80, 50);
    self.canSeePasswordButton.frame = CGRectMake(WIDTH-80-25, CGRectGetMaxY(self.codeTextField.frame), 80, 50);
    self.LineView.frame = CGRectMake(WIDTH-80-25, CGRectGetMaxY(self.userTextField.frame)+15, 1, 20);
    [self setNeedsLayout];
}

// 键盘弹出后的布局
- (void)afterAnimations
{
    if (iphone5S || iphone4S) {
        self.BGiconView.frame = CGRectMake((WIDTH-(105/2.0))/2.0, 46, 105/2.0, 105/2.0);
        self.userTextField.frame = CGRectMake(0, CGRectGetMaxY(self.BGiconView.frame)+28, WIDTH, 50);
        self.BGiconView.layer.cornerRadius = 105/2/2;
    }
    else{
        self.BGiconView.frame = CGRectMake((WIDTH-(129/2.0))/2.0, 107, 129/2.0, 129/2.0);
        self.userTextField.frame = CGRectMake(0, CGRectGetMaxY(self.BGiconView.frame)+45, WIDTH, 50);
        self.BGiconView.layer.cornerRadius = 129/2/2;
        
    }
    self.iconImageView.frame = CGRectMake(10, 10, self.BGiconView.frame.size.width-20, self.BGiconView.frame.size.height-20);
     self.iconImageView.layer.cornerRadius =(self.BGiconView.frame.size.width-20)/2;
    //self.userTextField.frame = CGRectMake(0, CGRectGetMaxY(self.InvitationTextField.frame), WIDTH, 50);
    self.codeTextField.frame = CGRectMake(0, CGRectGetMaxY(self.userTextField.frame), WIDTH-120, 50);
    self.passwordTextField.frame = CGRectMake(0, CGRectGetMaxY(self.codeTextField.frame), WIDTH-120, 50);
    self.registerButton.frame = CGRectMake(25, CGRectGetMaxY(self.passwordTextField.frame)+30, WIDTH-50, 40);
    self.LineView.frame = CGRectMake(WIDTH-80-25, CGRectGetMaxY(self.userTextField.frame)+15, 1, 20);
    self.XVerificationButton.frame = CGRectMake(WIDTH-80-25, CGRectGetMaxY(self.userTextField.frame), 80, 50);
    self.canSeePasswordButton.frame = CGRectMake(WIDTH-80-25, CGRectGetMaxY(self.codeTextField.frame), 80, 50);
    [self setNeedsLayout];
}

- (void)updateEnableState:(BOOL)enable hasLogin:(BOOL)hasLogin
{
    if (enable) {
        self.registerButton.enabled = YES;
        [self.registerButton setTitle:@"注册" forState:UIControlStateNormal];
    }
    else {
        self.registerButton.enabled = NO;
        [self.registerButton setTitle:hasLogin?@"注册中...":@"注册" forState:UIControlStateNormal];
    }
}

- (void)resignResponse
{
    [self.userTextField.textField resignFirstResponder];
    [self.passwordTextField.textField resignFirstResponder];
}

- (void)login
{
    
    if (self.userTextField.textField.text.length<=0){
        [JXTHUDHelper showHUDText:@"请输入手机号" type:@"error" inView:self];
        return ;
        
    }else if (self.userTextField.textField.text.length>0) {
        NSString *firstStr = [self.userTextField.textField.text substringToIndex:1];
        if (self.userTextField.textField.text.length != 11 || ![firstStr isEqualToString:@"1"]||self.userTextField.textField.text.length<=0) {
            [JXTHUDHelper showHUDText:@"请输入正确的手机号" type:@"error" inView:self];
            return ;
            
        }
        
    }else if (self.userTextField.textField.text.length<=0) {
        [JXTHUDHelper showHUDText:@"请输入验证码" type:@"error" inView:self];
        return ;
    }else if (self.codeTextField.textField.text.length<=0) {
        [JXTHUDHelper showHUDText:@"请输入验证码" type:@"error" inView:self];
        return ;
    } // 判断密码格式是否正确，并请求验证码
    if (![self checkPasswordTextField]) {
        [JXTHUDHelper showHUDText:@"请输入密码" type:@"error" inView:self];
        return ;
    }
    
    
    self.registerBlock(self.InvitationTextField.textField.text, self.userTextField.textField.text,self.codeTextField.textField.text,self.passwordTextField.textField.text);
}

#pragma mark - touchMethod
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    self.needAnimateAfterKeybordHide = YES;
    [self resignResponse];
}
#pragma mark - property
- (UIImageView *)iconImageView
{
    if (_iconImageView == nil) {
        _iconImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"AppIcon"]];
//        _iconImageView.clipsToBounds = YES;
//        _iconImageView.layer.borderColor = [UIColor whiteColor].CGColor;//边框颜色
//        _iconImageView.layer.borderWidth = 1;//边框宽度
    }
    return _iconImageView;
}
- (UIView *)BGiconView
{
    if (_BGiconView == nil) {
        _BGiconView = [[UIView alloc] init];
        _BGiconView.clipsToBounds = YES;
        _BGiconView.layer.borderColor = [UIColor whiteColor].CGColor;//边框颜色
        _BGiconView.layer.borderWidth = 1;//边框宽度
        _BGiconView.backgroundColor=MYYColorFromRGB(0xfb7768);;
    }
    return _BGiconView;
}


- (MYY_LoginTextField *)InvitationTextField
{
    if (_InvitationTextField == nil) {
        _InvitationTextField = [MYY_LoginTextField new];
        _InvitationTextField.textField.tag = 10000;
        _InvitationTextField.textField.keyboardType=UIKeyboardTypeNumberPad;
        // _userTextField.backgroundColor =MYYColorFromRGB(0xbceae5);
    }
    return _InvitationTextField;
}


- (MYY_LoginTextField *)userTextField
{
    if (_userTextField == nil) {
        _userTextField = [MYY_LoginTextField new];
        _userTextField.textField.tag = 10001;
        _userTextField.textField.keyboardType=UIKeyboardTypeNumberPad;
        // _userTextField.backgroundColor =MYYColorFromRGB(0xbceae5);
    }
    return _userTextField;
}

- (MYY_LoginTextField *)codeTextField
{
    if (_codeTextField == nil) {
        _codeTextField = [MYY_LoginTextField new];
        _codeTextField.textField.tag = 10002;
        _codeTextField.textField.keyboardType=UIKeyboardTypeNumberPad;
        // _userTextField.backgroundColor =MYYColorFromRGB(0xbceae5);
    }
    return _codeTextField;
}
- (MYY_LoginTextField *)passwordTextField
{
    if (_passwordTextField == nil) {
        _passwordTextField = [MYY_LoginTextField new];
        _passwordTextField.textField.tag = 10003;
        // _passwordTextField.backgroundColor =MYYColorFromRGB(0xbceae5);
    }
    return _passwordTextField;
}
- (UIButton *)registerButton
{
    if (_registerButton == nil) {
        _registerButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_registerButton.layer setMasksToBounds:YES];
        [_registerButton.layer setCornerRadius:20.0];//MYYColorFromRGB(0xffffff)
        [_registerButton setBackgroundImage:[[JXTColorHelper imageWithColor:MYYheadColor] stretchableImageWithLeftCapWidth:1 topCapHeight:1] forState:UIControlStateNormal];
        [_registerButton setBackgroundImage:[[JXTColorHelper imageWithColor:MYYheadColor] stretchableImageWithLeftCapWidth:1 topCapHeight:1] forState:UIControlStateDisabled];
        [_registerButton setBackgroundImage:[[JXTColorHelper imageWithColor:MYYheadColor] stretchableImageWithLeftCapWidth:1 topCapHeight:1] forState:UIControlStateSelected];
        [_registerButton setTitle:@"注册" forState:UIControlStateNormal];
        [_registerButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_registerButton setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
        _registerButton.layer.borderColor = [UIColor whiteColor].CGColor;//边框颜色
        _registerButton.layer.borderWidth = 1;//边框宽度
        
        [_registerButton setEnabled:NO];
        [_registerButton addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _registerButton;
}

- (UIView *)LineView
{
    if (_LineView == nil) {
        _LineView = [[UIView alloc] init];
        _LineView.backgroundColor =[UIColor whiteColor];
    }
    return _LineView;
}

- (CodeButton *)XVerificationButton
{
    if (_XVerificationButton == nil) {
        _XVerificationButton = [[CodeButton alloc] init];
        _XVerificationButton.backgroundColor = [UIColor clearColor];
        [_XVerificationButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_XVerificationButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _XVerificationButton.titleLabel.font =[UIFont systemFontOfSize:12];
        _XVerificationButton.timeOut =59;
        [_XVerificationButton addTarget:self action:@selector(veriButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _XVerificationButton;
}

- (UIButton *)canSeePasswordButton
{
    if (_canSeePasswordButton == nil) {
        _canSeePasswordButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_canSeePasswordButton setImage:[UIImage imageNamed:@"canSeePassclose"] forState:UIControlStateNormal];
        [_canSeePasswordButton setImage:[UIImage imageNamed:@"canSeePassopen"] forState:UIControlStateSelected];
        [_canSeePasswordButton addTarget:self action:@selector(canSeeButton:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _canSeePasswordButton;
}

#pragma mark - 是否关闭密码


-(void)canSeeButton:(UIButton *)btn{
    
    self.passwordTextField.textField.secureTextEntry = !self.passwordTextField.textField.isSecureTextEntry;
    btn.selected                    = !btn.selected;
}


#pragma mark - 验证码

-(void)veriButton:(CodeButton*)btn
{
   
    if (self.userTextField.textField.text.length<=0){
        [JXTHUDHelper showHUDText:@"请输入手机号" type:@"error" inView:nil];
        return ;
    }
    NSString *firstStr = [self.userTextField.textField.text substringToIndex:1];
    if (self.userTextField.textField.text.length != 11||![firstStr isEqualToString:@"1"]||self.userTextField.textField.text.length<=0) {
        [JXTHUDHelper showHUDText:@"请输入正确的手机号" type:@"error" inView:nil];
        return ;
    }
    
    
    self.MYXHttpManag =[[MYXHttpManager alloc]init];
    
    [self.MYXHttpManag identify:self.userTextField.textField.text success:^(NSString *dataStr) {
        [JXTHUDHelper showHUDText:@"发送成功" type:@"success" inView:nil];
    } failure:^(NSString *errorCode) {
        [JXTHUDHelper showHUDText:@"请稍后重试！" type:@"error" inView:nil];
    } netDown:^{
        
    }];
    
    [btn startCountdown];
    [JXTHUDHelper showHUDText:@"发送成功" type:@"success" inView:nil];
    
//    if (self.XVerificationB) {
//         self.XVerificationB(btn);
//    }
}



- (STStalker *)stalker
{
    if (_stalker == nil) {
        _stalker = [STStalker new];
    }
    return _stalker;
}

/** 检查手机号格式 */
- (BOOL)checkPhoneTextField {
    return self.userTextField.textField.text.length == 11;
}

/** 检查密码格式 */
- (BOOL)checkPasswordTextField {
    NSString *passwordText =self.passwordTextField.textField.text;
    
    return passwordText.length >= 6 && passwordText.length <= 20;
}

/** 检查验证码格式 */
- (BOOL)checkIdentifyingCodeTextField {
    return self.codeTextField.textField.text.length >= 4;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
